package com.sharkburner.aeris.servlet;

import java.io.BufferedWriter;
import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.sharkburner.aeris.bean.MessageResource;
import com.vaadin.Application;
import com.vaadin.terminal.gwt.server.AbstractApplicationServlet;

public class SpringVaadinServlet extends AbstractApplicationServlet {

	/** Class serial version unique identifier. */
	private static final long serialVersionUID = 1L;

	private Class<? extends Application> clazz;

	@Override
	public void init(ServletConfig config) throws ServletException {

		super.init(config);

		WebApplicationContext wac = WebApplicationContextUtils
				.getRequiredWebApplicationContext(config.getServletContext());

		Application application = (Application) wac.getBean("application",
				Application.class);

		clazz = application.getClass();
	}

	/**
	 * Gets the application from the Spring context.
	 * 
	 * @return The Spring bean named 'application'
	 */
	@Override
	protected Application getNewApplication(HttpServletRequest request)
			throws ServletException {

		WebApplicationContext wac = WebApplicationContextUtils
				.getRequiredWebApplicationContext(request.getSession()
						.getServletContext());

		return (Application) wac.getBean("application", Application.class);
	}

	/**
	 * @see com.vaadin.terminal.gwt.server.AbstractApplicationServlet#getApplicationClass()
	 */
	@Override
	protected Class<? extends Application> getApplicationClass()
			throws ClassNotFoundException {

		return clazz;
	}
	
	@Override
	protected void writeAjaxPageHtmlHeader(BufferedWriter page, String title,
			String themeUri, HttpServletRequest request) throws IOException {
		super.writeAjaxPageHtmlHeader(page, title, themeUri, request);
		
		WebApplicationContext wac = WebApplicationContextUtils
		.getRequiredWebApplicationContext(request.getSession()
				.getServletContext());
		
		MessageResource messageResource=wac.getBean(MessageResource.class);
		
		page.write(messageResource.getText("share.facebook.api"));
	}	
}
